package com.tanhua.dubbo.api;

import com.tanhua.dubbo.mongo.FriendApi;
import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class FriendApiImpl implements FriendApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 将好友关系双向绑定到关系表
     * @param userId 当前id
     * @param friendId 好友id
     */
    @Override
    public void save(Long userId, Long friendId) {
        //保存自己的好友数据
        Query query1 = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        //判断是否存在好友关系
        //不存在
        if(!mongoTemplate.exists(query1, Friend.class)){
            Friend friend=new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
        //保存好友的数据
        Query query2 = Query.query(Criteria.where("friendId").is(userId).and("userId").is(friendId));
        if(!mongoTemplate.exists(query1, Friend.class)){
            Friend friend=new Friend();
            friend.setUserId(friendId);
            friend.setFriendId(userId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
    }

    /**
     * 查询联系人
     * @param userId 用户id
     * @param page 页码
     * @param pagesize 当前页条数
     * @return 返回好友关系
     */
    @Override
    public List<Friend> findByUserId(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query,Friend.class);
    }
}
